////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2008 Michiel Helvensteijn                                    //
//                                                                            //
// This file is part of the Mist compiler.                                    //
//                                                                            //
// The Mist compiler is free software: you can redistribute it and/or modif   //
// it under the terms of the GNU General Public License as published by       //
// the Free Software Foundation, either version 3 of the License, or          //
// (at your option) any later version.                                        //
//                                                                            //
// The Mist compiler is distributed in the hope that it will be useful,       //
// but WITHOUT ANY WARRANTY; without even the implied warranty of             //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              //
// GNU General Public License for more details.                               //
//                                                                            //
// You should have received a copy of the GNU General Public License          //
// along with the Mist compiler.  If not, see <http://www.gnu.org/licenses/>. //
////////////////////////////////////////////////////////////////////////////////

#include "visitors/accesstypevisitor.hpp"

/******************************************************************************
 * Includes                                                                   *
 ******************************************************************************/

#include <boost/foreach.hpp>
#define foreach BOOST_FOREACH

#include <boost/format.hpp>
using boost::format;

#include <boost/shared_ptr.hpp>
using boost::dynamic_pointer_cast;

#include <typeinfo>

#include "ast/nodetypes.hpp"
#include "visitors/visitor.hpp"
#include "visitors/echovisitor.hpp"
#include "visitors/expressionnavigator.hpp"
#include "messages.hpp"
#include "common.hpp"
#include "accesstype.hpp"
#include "symboltree.hpp"

/******************************************************************************
 * AccessTypeVisitor Class                                                    *
 ******************************************************************************/

class AccessTypeVisitor : public ExpressionNavigator {
	public:
		
		AccessTypeVisitor(shared_ptr<Messages> messages) : ExpressionNavigator(messages) {}
		
		void visit(shared_ptr<ArithmeticOperation>   node);
		void visit(shared_ptr<FunctionCall>          node);
		void visit(shared_ptr<UnaryOperation>        node);
		void visit(shared_ptr<IntegerLiteral>        node);
		void visit(shared_ptr<BooleanLiteral>        node);
		void visit(shared_ptr<Null>                  node);
		void visit(shared_ptr<Assertion>             node);
		void visit(shared_ptr<IfStatement>           node);
		void visit(shared_ptr<WhileStatement>        node);
		void visit(shared_ptr<Assignment>            node);
		void visit(shared_ptr<IdAssignment>          node);
		void visit(shared_ptr<VariableDeclaration>   node);
		void visit(shared_ptr<Subscripting>          node);
		void visit(shared_ptr<ComparisonChain>       node);
		void visit(shared_ptr<AndChain>              node);
		void visit(shared_ptr<OrChain>               node);
		void visit(shared_ptr<ImpliesChain>          node);
		void visit(shared_ptr<ForStatement>          node);
		void visit(shared_ptr<Range>                 node);
		void visit(shared_ptr<Reference>             node);
		void visit(shared_ptr<BooleanPointerLiteral> node);
		void visit(shared_ptr<IntegerPointerLiteral> node);
};

/******************************************************************************
 * Function Implementations                                                   *
 ******************************************************************************/

void set_access_types(shared_ptr<Node> node, shared_ptr<Messages> messages) {
	assert(node);
	assert(messages);
	
	shared_ptr<AccessTypeVisitor> visitor(new AccessTypeVisitor(messages));
	
	node->accept(visitor);
}

/******************************************************************************/

void AccessTypeVisitor::visit(shared_ptr<ArithmeticOperation> node) {
	assert(node);
	
	ExpressionNavigator::visit(node);
	
	if (node->left_operand()->access_type().value.readable == false)
		messages()->add("val-readable-error", node->left_operand()->location())
			% (format("the left side of the %1% operator") % to_string(node->operator_type()));
	
	if (node->right_operand()->access_type().value.readable == false)
		messages()->add("val-readable-error", node->right_operand()->location())
			% (format("the right side of the %1% operator") % to_string(node->operator_type()));
	
	node->set_access_type(AccessType(false, false, true, false));
}

void AccessTypeVisitor::visit(shared_ptr<FunctionCall> node) {
	assert(node);
	
	ExpressionNavigator::visit(node);
	
	if (typeid(*node->base()->type()) == typeid(FunctionType)) {
		shared_ptr<FunctionType> ftype = dynamic_pointer_cast<FunctionType>(node->base()->type());
		for (unsigned int i = 0; i < node->parameter_count() && i < ftype->parameter_type_count(); ++i) {
			if ((   typeid(*node->parameters()[i]) == typeid(BooleanPointerLiteral)
			     || typeid(*node->parameters()[i]) == typeid(IntegerPointerLiteral)
			     || node->parameters()[i]->equals(Null()))
			    && ftype->parameter_types()[i].policy->identityPassed
			    && ftype->parameter_types()[i].policy->identityReturned == false)
				continue;
			
			AccessType required = ftype->parameter_types()[i].policy->actualAccess;
			AccessType actual   = node->parameters()[i]->access_type();
			
			if (required.identity.readable && !actual.identity.readable)
				messages()->add("id-readable-error", node->parameters()[i]->location())
					% (format("the %1% actual parameter of the function-call") % ordinal(i+1));
			
			if (required.identity.writable && !actual.identity.writable)
				messages()->add("id-writable-error", node->parameters()[i]->location())
					% (format("the %1% actual parameter of the function-call") % ordinal(i+1));
			
			if (required.value.readable && !actual.value.readable)
				messages()->add("val-readable-error", node->parameters()[i]->location())
					% (format("the %1% actual parameter of the function-call") % ordinal(i+1));
			
			if (required.value.writable && !actual.value.writable)
				messages()->add("val-writable-error", node->parameters()[i]->location())
					% (format("the %1% actual parameter of the function-call") % ordinal(i+1));
		}
	}
	
	node->set_access_type(AccessType(false, false, true, false));
}

void AccessTypeVisitor::visit(shared_ptr<UnaryOperation> node) {
	assert(node);
	
	ExpressionNavigator::visit(node);
	
	if (node->operand()->access_type().value.readable == false)
		messages()->add("val-readable-error", node->operand()->location())
			% (format("the operand of the %1% operator") % to_string(node->operator_type()));
	
	node->set_access_type(AccessType(false, false, true, false));
}

void AccessTypeVisitor::visit(shared_ptr<IntegerLiteral> node) {
	assert(node);
	
	node->set_access_type(AccessType(false, false, true, false));
}

void AccessTypeVisitor::visit(shared_ptr<BooleanLiteral> node) {
	assert(node);
	
	node->set_access_type(AccessType(false, false, true, false));
}

void AccessTypeVisitor::visit(shared_ptr<Null> node) {
	assert(node);
	
	node->set_access_type(AccessType(true, false, false, false));
}

void AccessTypeVisitor::visit(shared_ptr<Assertion> node) {
	assert(node);
	
	ExpressionNavigator::visit(node);
	
	if (node->condition_is_set())
		if (node->condition()->access_type().value.readable == false)
			messages()->add("val-readable-error", node->condition()->location())
				% "the assertion condition";
}

void AccessTypeVisitor::visit(shared_ptr<IfStatement> node) {
	assert(node);
	
	ExpressionNavigator::visit(node);
	
	if (node->condition()->access_type().value.readable == false)
		messages()->add("val-readable-error", node->condition()->location())
			% "the if-statement condition";
}

void AccessTypeVisitor::visit(shared_ptr<WhileStatement> node) {
	assert(node);
	
	ExpressionNavigator::visit(node);
	
	if (node->condition()->access_type().value.readable == false)
		messages()->add("val-readable-error", node->condition()->location())
			% "the while-statement condition";
}

void AccessTypeVisitor::visit(shared_ptr<Assignment> node) {
	assert(node);
	
	ExpressionNavigator::visit(node);
	
	if (node->left_side()->access_type().value.writable == false)
		messages()->add("val-writable-error", node->left_side()->location())
			% "the left side of the assignment";
	
	if (node->right_side()->access_type().value.readable == false)
		messages()->add("val-readable-error", node->right_side()->location())
			% "the right side of the assignment";
	
	node->set_access_type(AccessType(true, true, true, true));
}

void AccessTypeVisitor::visit(shared_ptr<IdAssignment> node) {
	assert(node);
	
	ExpressionNavigator::visit(node);
	
	if (node->left_side()->access_type().identity.writable == false)
		messages()->add("id-writable-error", node->left_side()->location())
			% "the left side of the identity assignment";
	
	if (node->right_side()->access_type().identity.readable == false)
		messages()->add("id-readable-error", node->right_side()->location())
			% "the right side of the identity assignment";
	
	if (   typeid(*node->right_side()) != typeid(BooleanPointerLiteral)
	    && typeid(*node->right_side()) != typeid(IntegerPointerLiteral)
	    && !node->right_side()->equals(Null())
	    && node->right_side()->access_type().value.writable == false)
		messages()->add("val-writable-error", node->right_side()->location())
			% "the right side of the identity assignment";
	
	node->set_access_type(AccessType(true, true, true, true));
}

void AccessTypeVisitor::visit(shared_ptr<VariableDeclaration> node) {
	assert(node);
	
	ExpressionNavigator::visit(node);
	
	foreach (VarDec varDec, node->variables()) {
		if (varDec.is_initialized()) {
			if (varDec.init_is_identity) {
				if (varDec.init->access_type().identity.readable == false)
					messages()->add("id-readable-error", varDec.init->location())
						% "the variable identity initialization";
				if (   typeid(*varDec.init) != typeid(BooleanPointerLiteral)
				    && typeid(*varDec.init) != typeid(IntegerPointerLiteral)
				    && !varDec.init->equals(Null())
				    && varDec.init->access_type().value.writable == false)
					messages()->add("val-writable-error", varDec.init->location())
						% "the variable identity initialization";
			} else {
				if (varDec.init->access_type().value.readable == false)
					messages()->add("val-readable-error", varDec.init->location())
						% "the variable initialization";
				if (node->type()->weak_pointer())
					messages()->add("weak-val-init", varDec.init->location());
			}
		}
	}
}

void AccessTypeVisitor::visit(shared_ptr<Subscripting> node) {
	assert(node);
	
	ExpressionNavigator::visit(node);
	
	if (node->subscript()->access_type().value.readable == false)
		messages()->add("val-readable-error", node->subscript()->location())
			% "the subscript";
	
	node->set_access_type(node->base()->access_type());
}

void AccessTypeVisitor::visit(shared_ptr<ComparisonChain> node) {
	assert(node);
	
	ExpressionNavigator::visit(node);
	
	unsigned number = 1;
	unsigned lastError = 0;
	foreach (Comparison operation, node->comparisons()) {
		if (operation.comparison_operator == IdentityOperator || operation.comparison_operator == NotIdentityOperator) {
			if (operation.left_operand->access_type().identity.readable == false && lastError != number) {
				messages()->add("id-readable-error", operation.left_operand->location())
					% (format("the %1% operand of the %2%")
						% ordinal(number)
						% (node->comparison_operator_count() > 1 ? "comparison-chain" : "identity-test"));
			}
			if (operation.right_operand->access_type().identity.readable == false) {
				messages()->add("id-readable-error", operation.left_operand->location())
					% (format("the %1% operand of the %2%")
						% ordinal(number + 1)
						% (node->comparison_operator_count() > 1 ? "comparison-chain" : "identity-test"));
				lastError = number + 1;
			}
		} else {
			if (operation.left_operand->access_type().value.readable == false && lastError != number) {
				messages()->add("val-readable-error", operation.left_operand->location())
					% (format("the %1% operand of the %2%")
						% ordinal(number)
						% (node->comparison_operator_count() > 1 ? "comparison-chain" : "comparison"));
			}
			if (operation.right_operand->access_type().value.readable == false) {
				messages()->add("val-readable-error", operation.right_operand->location())
					% (format("the %1% operand of the %2%")
						% ordinal(number+1)
						% (node->comparison_operator_count() > 1 ? "comparison-chain" : "comparison"));
				lastError = number + 1;
			}
		}
		++number;
	}
	
	node->set_access_type(AccessType(false, false, true, false));
}

void AccessTypeVisitor::visit(shared_ptr<AndChain> node) {
	assert(node);
	
	ExpressionNavigator::visit(node);
	
	unsigned number = 1;
	foreach (shared_ptr<Expression> operand, node->operands()) {
		if (operand->access_type().value.readable == false)
			messages()->add("val-readable-error", operand->location())
				% (format("the %1% operand of the logical conjunction") % ordinal(number));
		++number;
	}
	
	node->set_access_type(AccessType(false, false, true, false));
}

void AccessTypeVisitor::visit(shared_ptr<OrChain> node) {
	assert(node);
	
	ExpressionNavigator::visit(node);
	
	unsigned number = 1;
	foreach (shared_ptr<Expression> operand, node->operands()) {
		if (operand->access_type().value.readable == false)
			messages()->add("val-readable-error", operand->location())
				% (format("the %1% operand of the logical disjunction") % ordinal(number));
		++number;
	}
	
	node->set_access_type(AccessType(false, false, true, false));
}

void AccessTypeVisitor::visit(shared_ptr<ImpliesChain> node) {
	assert(node);
	
	ExpressionNavigator::visit(node);
	
	unsigned number = 1;
	foreach (shared_ptr<Expression> operand, node->operands()) {
		if (operand->access_type().value.readable == false)
			messages()->add("val-readable-error", operand->location())
				% (format("the %1% operand of the %2%")
					% ordinal(number)
					% (node->operand_count() > 2 ? "implication-chain" : "implication"));
		++number;
	}
	
	node->set_access_type(AccessType(false, false, true, false));
}

void AccessTypeVisitor::visit(shared_ptr<ForStatement> node) {
	assert(node);
	
	ExpressionNavigator::visit(node);
	
	if (node->range()->access_type().value.readable == false)
		messages()->add("val-readable-error", node->range()->location())
			% "the for-statement range";
}

void AccessTypeVisitor::visit(shared_ptr<Range> node) {
	assert(node);
	
	ExpressionNavigator::visit(node);
	
	if (node->lower_bound()->access_type().value.readable == false)
		messages()->add("val-readable-error", node->lower_bound()->location())
			% "the lower-bound of the range";
	
	if (node->upper_bound()->access_type().value.readable == false)
		messages()->add("val-readable-error", node->upper_bound()->location())
			% "the upper-bound of the range";
	
	if (node->step()->access_type().value.readable == false)
		messages()->add("val-readable-error", node->step()->location())
			% "the step-size of the range";
	
	node->set_access_type(AccessType(false, false, true, false));
}

void AccessTypeVisitor::visit(shared_ptr<Reference> node) {
	assert(node);
	
	if (node->symbol_is_set()) {
		node->set_access_type(node->symbol()->access_type());
	} else {
		// We give the symbol id:rw,val:rw to avoid further error messages about the same issue
		node->set_access_type(AccessType(true, true, true, true));
	}
}

void AccessTypeVisitor::visit(shared_ptr<BooleanPointerLiteral> node) {
	assert(node);
	
	ExpressionNavigator::visit(node);
	
	if (node->value()->access_type().value.readable == false)
		messages()->add("val-readable-error", node->value()->location())
			% "the value of the boolean pointer literal";
	
	node->set_access_type(AccessType(true, false, true, false));
}

void AccessTypeVisitor::visit(shared_ptr<IntegerPointerLiteral> node) {
	assert(node);
	
	ExpressionNavigator::visit(node);
	
	if (node->value()->access_type().value.readable == false)
		messages()->add("val-readable-error", node->value()->location())
			% "the value of the integer pointer literal";
	
	node->set_access_type(AccessType(true, false, true, false));
}
